import mapper from "../mapper/BaseMapper.js"
import BeanUtils from '../utils/BeanUtils.js'

import UserVO from "../domain/vo/UserVo.js"
import LwtUtils from "../utils/LwtUtils.js"
import AuthProperties from '../properties/AtuhProperites.js'
import User from "../domain/pojo/User.js"

export class UserServiceImpl {


    getUserInfoById(userId) {
        const table = mapper.get("tb_user")

        for (let row of table) {
            if (row.id == userId) {
                return BeanUtils.toBean(new UserVO(), row)
            }
        }

        console.log("mapper table", table)
        // 不存在
        throw new Error("用户不存在!")
    }

    updateUserInfo(userId, name, signature, email, gender, password) {
        const table = mapper.get("tb_user")

        let item = null
        for (let row of table) {
            if (row.id == userId) {
                item = row
                break
            }
        }

        if (!item) {
            throw new Error("用户不存在!")
        }

        item.name = name || item.name
        item.email = email || item.email
        item.gender = gender || item.gender
        item.password = password || item.password
        item.signature = signature || item.signature

        mapper.save("tb_user")
    }

    // 返回一个token
    login(username, password) {
        let user = null
        const table = mapper.get("tb_user")
        for (let i = 0; i < table.length; i ++) {
            if (table[i].username == username) {
                if (table[i].password != password) {
                    throw new Error("用户名和密码不匹配")
                }
                user = table[i]
                break
            }
        }
        if (!user) {
            throw new Error("用户不存在!")
        }
        
        const claims = {
            userId: user.id
        }

        return LwtUtils.builder
            .setSignature(AuthProperties.lwtKey)
            .setExpiration(new Date().valueOf() + 1000 * 60 * 60 * 6)
            .setClaims(claims).compact();
    }


    registry(username, password, email) {
        // 用户或邮箱是否存在，同时记录id最大值，这里的id就直接用递增的id了
        let maxId = 0
        const table = mapper.get("tb_user")
        for (let row of table) {
            if (row.username == username || row.email == email) {
                if (row.username == username) {
                    throw new Error("该用户已被注册!")
                }
                throw new Error("该邮箱已被其他用户使用")
            }
            maxId = Math.max(maxId, row.id)
        }
        // 校验成功，添加用户
        table.push(new User(maxId + 1, username, password, email))

        mapper.save("tb_user")
    }

}